import { BallScript } from "./BallScript";
import GameManager from "./GameManager";
import { StopWatchScript } from "./StopWatchScript";

const { regClass, property } = Laya;

@regClass()
export class ScenePlayScript extends Laya.Script {
    //declare owner : Laya.Sprite3D;
    declare owner: Laya.Sprite;

    @property(String)
    public text: string = "";
    toolList: Laya.List;
    toolInfo: any[];
    assembleList: Laya.List;
    assembleDate: any[];
    pipe: Laya.Image;

    //水管是否选中
    pipeSelected: boolean = false;
    selectInfo: any = {};
    checkIndex: number;
    inputPort: number;
    stopswitchSp: any;
    levelLabel: Laya.Label;
    @property({ type: Laya.Prefab })
    public ball: Laya.Prefab;
    ballContainer: Laya.Sprite;
    assambleContainer: Laya.Image;
    ballPrefab: Laya.Prefab;
    constructor() {
        super();
    }
    //组件被激活后执行，此时所有节点和组件均已创建完毕，此方法只执行一次
    //onAwake(): void {} 


    //组件被启用后执行，例如节点被添加到舞台后
    onEnable(): void {
        this.intercom();
        this.initUI();
        this.initLevel();
        this.soundManager();

        const path:string="./resources/Prefabs/ballPrefab.lh";
        Laya.loader.load(path).then((res)=>{
            console.log("【ball】",res);
            this.ballPrefab=res;
        })
    }
    //管理内部通讯基于Laya的监听
    intercom() {
        Laya.stage.on(Laya.Event.MESSAGE, this, (data: any) => {
            switch (data.type) {
                case "missionFail": {
                    console.log("失败了");
                    Laya.Scene.open("./resources/Scenes/Dialog_Fail.ls", false);
                    // Laya.stage.event(Laya.Event.MESSAGE, { type: "missionFail" });

                } break;
                case "gameStart": {
                    this.stopswitchSp.coolDown();
                } break;
                case "tryAgain": {
                    console.log("重新开始");
                    Laya.timer.once(1000, this, () => {
                        this.stopswitchSp.reset(20000);//
                        this.initLevel();//
                    })

                } break;
                case "success": {
                    console
                    Laya.timer.once(1000, this, () => {
                        GameManager.getInstance().level++;
                        localStorage.setItem("level", GameManager.getInstance().level.toString());
                        this.stopswitchSp.reset(20000);
                        this.initLevel();
                    })
                }

            }
        });
    }
    initUI() {
        this.toolInfo = GameManager.getInstance().toolInfo;
        // [
        //     { type: "pipe01", pipeImage: "atlas/img/pipe01.png", describe: "左右", port1: 1, port2: 3 },
        //     { type: "pipe02", pipeImage: "atlas/img/pipe02.png", describe: "上下", port1: 2, port2: 4 },
        //     { type: "pipe03", pipeImage: "atlas/img/pipe03.png", describe: "左下", port1: 1, port2: 4 },
        //     { type: "pipe04", pipeImage: "atlas/img/pipe04.png", describe: "右下", port1: 3, port2: 4 },
        //     { type: "pipe05", pipeImage: "atlas/img/pipe05.png", describe: "上右", port1: 2, port2: 3 },
        //     { type: "pipe06", pipeImage: "atlas/img/pipe06.png", describe: "上左", port1: 2, port2: 1 },
        // ];
        let stopswitch = this.owner.getChildByName("stopwatch");
        this.stopswitchSp = stopswitch.getComponent(StopWatchScript);

        this.pipe = this.owner.getChildByName("pipe") as Laya.Image;
        this.pipe.visible = false;

        this.assembleList = this.owner.getChildByName("assembleList") as Laya.List;
        this.assembleList.renderHandler = new Laya.Handler(this, this.renderAssembleList);
        this.assembleList.mouseHandler = new Laya.Handler(this, this.mouseOnAssembleList);

        this.toolList = this.owner.getChildByName("toolList") as Laya.List;
        this.toolList.array = this.toolInfo;
        this.toolList.renderHandler = new Laya.Handler(this, this.renderToolList);
        this.toolList.mouseHandler = new Laya.Handler(this, this.mouseOnToolList);

        this.levelLabel = this.owner.getChildByName("levelLabel") as Laya.Label;
        if (!this.levelLabel) {
            console.error("levelLabel not found");
        }
        this.ballContainer = this.owner.getChildByName("ballContainer") as Laya.Sprite;
        this.ballContainer.width = Laya.stage.width;
        this.ballContainer.height = Laya.stage.height;

        this.assambleContainer = this.owner.getChildByName("assambleContainer") as Laya.Image;

    }
    //初始化关卡
    initLevel(): void {
        this.initAssemble();
        this.assembleList.array = this.assembleDate;
        // this.levelLabel.text = "关卡" + GameManager.getInstance().level;
        if (this.levelLabel) {
            this.levelLabel.text = "关卡" + GameManager.getInstance().level;
        } else {
            console.error("levelLabel is not initialized");
        }
        Laya.Scene.open("./resources/Scenes/Dialog_Start.ls", false);
    };


    mouseOnToolList(e: Laya.Event, index: number) {
        // console.log("【mouseOnToolList】", index, "【e.type】", e.type);
        if (e.type === "mousedown") {
            this.selectInfo = this.toolList.array[index];
            this.pipeSelected = true;
            this.pipe.skin = this.selectInfo.pipeImage;
            this.pipe.pos(Laya.InputManager.mouseX, Laya.InputManager.mouseY);
            this.pipe.visible = true;
        }
    }
    mouseOnAssembleList(e: Laya.Event, index: number) {
        // console.log("【mouseOnToolList】", index, "【e.type】", e.type);
        if (e.type === "mouseup") {
            if (index === 0 || index === 8) return;
            this.assembleDate[index].type = this.selectInfo.type;
            this.assembleDate[index].pipeImage = this.selectInfo.pipeImage;
            this.assembleDate[index].port1 = this.selectInfo.port1;
            this.assembleDate[index].port2 = this.selectInfo.port2;

            this.assembleList.array = this.assembleDate;

            this.checkConnected();
        }


    }

    //核对连通性
    checkConnected() {
        this.checkIndex = 0;
        this.inputPort = 3;
        this.chcking(this.checkIndex, this.inputPort);
    }
    chcking(checkIndex: number, inputPort: number) {
        let result = this.checkUnit(checkIndex, inputPort);
        if (result.connected === true) {
            console.log("成功了！")
            this.success();
        } else {
            if (result.nextIndex !== -1) {
                this.chcking(result.nextIndex, result.nextInputPort);
            }
        }
    }


    //链接成功的方法
    success() {
        this.selectInfo = {};
        this.pipeSelected = false;
        this.pipe.visible = false;

        console.log("弹出对话框链接成功");
        this.stopswitchSp.stopRound(true);
        Laya.Scene.open("./resources/Prefabs/Dialog_Success.lh", false);
        for (let i = 0; i < 5; i++) {
            this.addBall(i *200);
        }

    }
    //添加小球
    addBall(delay: number = 0) {
      
        let x2 = this.assambleContainer.x;
        let y2 = this.assambleContainer.y + 115;
        let x3 = this.assambleContainer.x + this.assambleContainer.width;
        let y3 = this.assambleContainer.y + 515;
        let ball = Laya.Pool.getItemByCreateFun("ball", this.ball.create, this.ball) as Laya.Sprite;
        let ballSp = ball.getComponent(BallScript);
        ballSp.initBall(-100, y2, x2, y2, x3, y3, delay);
        this.ballContainer.addChild(ball);
    }
    checkUnit(checkIndex: number, inputPort: number) {
        let nextIndex = -1;
        let nextInputPort = 0;
        let connected = false;
        let connectPort = 0;
        switch (inputPort) {
            case 1: connectPort = 3;
                break;
            case 2: connectPort = 4;
                break;
            case 3: connectPort = 1;
                break;
            case 4: connectPort = 2;
                break;
        }

        //检查当前单元格
        let currentUnit = this.assembleDate[checkIndex];
        let port1 = currentUnit.port1;
        let port2 = currentUnit.port2;

        //当前单元格为空
        if (port1 === 0 && port2 === 0) {

        } else if (checkIndex === 8) {
            if (connectPort === port1 || connectPort === port2) {
                connected = true;
            }
        } else {
            if (connectPort === port1) {
                nextInputPort = port2;
            }
            if (connectPort === port2) {
                nextInputPort = port1;
            }
            //存在有效出口
            if (connectPort !== nextInputPort) {
                switch (nextInputPort) {
                    //左
                    case 1: {
                        if (checkIndex === 0 || checkIndex === 3 || checkIndex === 6) {
                            nextIndex = -1;
                        } else {
                            nextIndex = checkIndex - 1;
                        }
                    }
                        break;
                    //上
                    case 2: {
                        if (checkIndex === 0 || checkIndex === 1 || checkIndex === 2) {
                            nextIndex = -1;
                        } else {
                            nextIndex = checkIndex - 3;
                        }
                    }
                        break;
                    //右
                    case 3: {
                        if (checkIndex === 2 || checkIndex === 5) {
                            nextIndex = -1;
                        } else {
                            nextIndex = checkIndex + 1;
                        }
                    }
                        break;
                    //下
                    case 4: {
                        if (checkIndex === 6 || checkIndex === 7) {
                            nextIndex = -1;
                        } else {
                            nextIndex = checkIndex + 3;
                        }
                    }
                        break;
                    default: {
                        nextIndex = -1;
                    }
                        break;
                }
            }
        }
        return { nextIndex, nextInputPort, connected };
    }

    onMouseDrag(evt: Laya.Event): void {
        // console.log("【onMouseDrag】", evt.type);
        this.pipe.pos(Laya.InputManager.mouseX, Laya.InputManager.mouseY);
    }

    onMouseDragEnd(evt: Laya.Event): void {
        // console.log("【onMouseDragEnd】", evt.type);
        this.selectInfo = {};
        this.pipeSelected = false;
        this.pipe.visible = false;
    }
    // 初始化关卡数据
    initAssemble() {
        this.assembleDate = [
            { index: 0, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 1, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 2, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 3, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 4, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 5, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 6, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 7, type: "", pipeImage: "", port1: 0, port2: 0 },
            { index: 8, type: "", pipeImage: "", port1: 0, port2: 0 },
        ];

        // assembleData位置0初始化，pipe01|pipe03
        let random = Math.random();
        if (random < 0.5) {
            this.assembleDate[0].type = this.toolInfo[0].type;
            this.assembleDate[0].pipeImage = this.toolInfo[0].pipeImage;
            this.assembleDate[0].port1 = this.toolInfo[0].port1;
            this.assembleDate[0].port2 = this.toolInfo[0].port2;
        } else {
            this.assembleDate[0].type = this.toolInfo[2].type;
            this.assembleDate[0].pipeImage = this.toolInfo[2].pipeImage;
            this.assembleDate[0].port1 = this.toolInfo[2].port1;
            this.assembleDate[0].port2 = this.toolInfo[2].port2;
        }


        // assembleData位置8初始化，pipe01|pipe05
        random = Math.random();
        if (random > 0.5) {
            this.assembleDate[8].type = this.toolInfo[0].type;
            this.assembleDate[8].pipeImage = this.toolInfo[0].pipeImage;
            this.assembleDate[8].port1 = this.toolInfo[0].port1;
            this.assembleDate[8].port2 = this.toolInfo[0].port2;
        } else {
            this.assembleDate[8].type = this.toolInfo[4].type;
            this.assembleDate[8].pipeImage = this.toolInfo[4].pipeImage;
            this.assembleDate[8].port1 = this.toolInfo[4].port1;
            this.assembleDate[8].port2 = this.toolInfo[4].port2;
        }
    };








    renderToolList(item: Laya.Box, index: number) {
        let dataSource = item.dataSource;
        let pipeImage = item.getChildByName("pipeImage") as Laya.Image;
        pipeImage.skin = dataSource.pipeImage;
    };
    renderAssembleList(item: Laya.Box, index: number) {
        let dataSource = item.dataSource;
        let pipeImage = item.getChildByName("pipeImage") as Laya.Image;
        pipeImage.skin = dataSource.pipeImage;

        let aimPrefab = item.getChildByName("aimPrefab") as Laya.UIComponent;
        if (dataSource.type === "" || typeof dataSource.type === "undefined") {
            aimPrefab.visible = true;
        } else {
            aimPrefab.visible = false;
        }

    };

    //背景音乐管理
    soundManager() {
        Laya.SoundManager.playMusic("./resources/audio/background.mp3", 0);
        let checkSound =this.owner.getChildByName("checkSound") as Laya.CheckBox;
        checkSound.selected=false;
        checkSound.on(Laya.Event.CLICK,this,()=>{
            //因为素材反向
            if(checkSound.selected===false){
                Laya.SoundManager.playMusic("./resources/audio/background.mp3", 0);
           
            }else{
                Laya.SoundManager.stopAll();
            }
        })
    }
    //组件被禁用时执行，例如从节点从舞台移除后
    //onDisable(): void {}

    //第一次执行update之前执行，只会执行一次
    //onStart(): void {}

    //手动调用节点销毁时执行
    //onDestroy(): void {}

    //每帧更新时执行，尽量不要在这里写大循环逻辑或者使用getComponent方法
    //onUpdate(): void {}

    //每帧更新时执行，在update之后执行，尽量不要在这里写大循环逻辑或者使用getComponent方法
    //onLateUpdate(): void {}

    //鼠标点击后执行。与交互相关的还有onMouseDown等十多个函数，具体请参阅文档。
    //onMouseClick(): void {}
}